# qa_web.py
import os
import uuid
from flask import Flask, request, render_template_string, jsonify, session
# 导入增强版 HistoryMemory
from history1 import HistoryMemory
import time
import random
from agent2 import EnterpriseAgentSystem  # 根据你的实际文件名调整

app = Flask(__name__)
# 设置一个密钥以启用 Flask sessions (用于存储当前会话 ID)
app.secret_key = os.environ.get("SECRET_KEY", "your_default_secret_key_change_this")

# --- 初始化 HistoryMemory ---
# 可以根据需要调整参数
history_memory = HistoryMemory(max_sessions=10, max_turns_per_session=20)

# --- 初始化 EnterpriseAgentSystem ---
# 请根据你的实际 FAISS 索引路径进行修改
FAISS_INDEX_PATH = "faiss_index"  # <--- 修改为你的实际路径
try:
    enterprise_agent = EnterpriseAgentSystem(faiss_index_path=FAISS_INDEX_PATH)
    print("✅ EnterpriseAgentSystem 初始化成功")
except Exception as e:
    print(f"❌ EnterpriseAgentSystem 初始化失败: {e}")
    enterprise_agent = None  # 如果初始化失败，后续调用需要检查


def real_agent_execute(query, context=""):
    """
    使用真实的 EnterpriseAgentSystem 执行查询，并利用上下文。
    """
    if not enterprise_agent:
        return "❌ Agent 系统未初始化，请检查日志。"

    # 1. 构造包含上下文的完整提示
    #    这里我们简单地将上下文作为前缀添加到查询中。
    #    你的 Ollama 模型 (qwen3:4b) 应该能够处理这种格式的长输入。
    full_query = f"请基于以下对话历史和文档知识回答问题。\n\n对话历史:\n{context}\n\n问题:\n{query}"

    # 2. 调用你的 Agent
    #    假设 execute_query 可以处理这种格式的查询。
    #    如果你的 Agent 内部已经处理了文档检索和 Prompt 构造，
    #    你可以直接传入 full_query。
    #    或者，如果你需要更精细的控制，可以在这里调用 DocumentStorage
    #    和 ReactAgentSystem 的方法。
    try:
        # 这里我们假设 execute_query 会处理所有逻辑
        # 如果需要区分 React 和 ZeroShot，可以根据 context 或其他逻辑决定
        # 注意：execute_query 会打印到 stdout，这里我们捕获返回值
        agent_response = enterprise_agent.execute_query(full_query, user_react=True)
        return agent_response
    except Exception as e:
        print(f"Agent 执行出错: {e}")
        return f"❌ 执行查询时发生错误: {str(e)}"


def mock_agent_execute(query, context=""):
    """模拟 Agent 执行，包含上下文"""
    time.sleep(1)  # 模拟处理延迟
    # 简单地将查询和上下文的一部分作为回复返回，以模拟上下文理解
    context_summary = context.split('\n')[-2:] if context else ["无上下文"]
    context_str = " ".join(context_summary)
    # 添加一些随机性使回复更有趣
    greetings = ["你好", "明白了", "收到"]
    responses = [
        f"{random.choice(greetings)}！关于'{query}'，结合之前的对话({context_str[:50]}...)，我认为...",
        f"根据你的问题 '{query}' 和我们之前的交流，我的看法是...",
        f"查询 '{query}' 已处理。参考上下文: {context_str[:30]}...，答案是..."
    ]
    return random.choice(responses)


# --- HTML 模板 ---
HTML_TEMPLATE = """
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>低空导航知识库</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#165DFF',
                        secondary: '#36CFC9',
                        neutral: {
                            100: '#F5F7FA',
                            200: '#E5E6EB',
                            300: '#C9CDD4',
                            400: '#86909C',
                            500: '#4E5969',
                            600: '#272E3B',
                            700: '#1D2129',
                        },
                        success: '#00B42A',
                        info: '#165DFF',
                    },
                    fontFamily: {
                        inter: ['Inter', 'system-ui', 'sans-serif'],
                    },
                    boxShadow: {
                        'card': '0 2px 14px 0 rgba(0, 0, 0, 0.06)',
                        'hover': '0 6px 20px 0 rgba(0, 0, 0, 0.08)',
                    }
                },
            }
        }
    </script>
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .scrollbar-hide {
                -ms-overflow-style: none;
                scrollbar-width: none;
            }
            .scrollbar-hide::-webkit-scrollbar {
                display: none;
            }
            .text-balance {
                text-wrap: balance;
            }
        }
    </style>
</head>
<body class="font-inter bg-neutral-100 text-neutral-700 h-screen flex flex-col overflow-hidden">
    <!-- 顶部导航栏 -->
    <header class="bg-white shadow-sm border-b border-neutral-200 z-10">
        <div class="container mx-auto px-4 py-3 flex items-center justify-between">
            <div class="flex items-center space-x-3">
                <i class="fa fa-compass text-primary text-2xl"></i>
                <h1 class="text-[clamp(1.2rem,3vw,1.5rem)] font-semibold text-neutral-700">低空导航知识库</h1>
            </div>
            <div class="flex items-center space-x-4">
                <button class="text-neutral-500 hover:text-primary transition-colors duration-200">
                    <i class="fa fa-question-circle"></i>
                </button>
                <button class="text-neutral-500 hover:text-primary transition-colors duration-200">
                    <i class="fa fa-cog"></i>
                </button>
            </div>
        </div>
    </header>

    <div class="flex flex-1 overflow-hidden">
        <!-- 左侧边栏 - 会话列表 -->
        <aside class="w-72 bg-white border-r border-neutral-200 flex flex-col hidden md:flex transition-all duration-300 ease-in-out" id="sidebar">
            <div class="p-4 border-b border-neutral-200">
                <div class="flex items-center justify-between mb-2">
                    <h2 class="font-medium text-neutral-700">会话历史</h2>
                    <span class="text-xs bg-primary/10 text-primary px-2 py-0.5 rounded-full" id="session-count">0 个会话</span>
                </div>
                <button id="new-session-btn" class="w-full bg-primary hover:bg-primary/90 text-white rounded-lg py-2.5 px-4 flex items-center justify-center space-x-2 transition-all duration-200 shadow-sm hover:shadow">
                    <i class="fa fa-plus text-sm"></i>
                    <span>新建会话</span>
                </button>
            </div>

            <div class="flex-1 overflow-y-auto scrollbar-hide p-2" id="session-list">
                <!-- 会话列表将通过 JS 动态填充 -->
                <div class="text-neutral-400 text-center py-10">
                    <i class="fa fa-comments-o text-4xl mb-3 opacity-30"></i>
                    <p>暂无会话记录</p>
                </div>
            </div>

            <div class="p-3 border-t border-neutral-200">
                <button id="clear-all-sessions-btn" class="w-full text-neutral-500 hover:text-primary text-sm py-2 flex items-center justify-center transition-colors duration-200">
                    <i class="fa fa-trash-o mr-2"></i>
                    清除所有会话
                </button>
            </div>
        </aside>

        <!-- 移动端侧边栏切换按钮 -->
        <button id="sidebar-toggle" class="md:hidden fixed left-4 bottom-20 bg-primary text-white rounded-full w-12 h-12 flex items-center justify-center shadow-lg z-20">
            <i class="fa fa-bars"></i>
        </button>

        <!-- 右侧主内容区 -->
        <main class="flex-1 flex flex-col overflow-hidden">
            <!-- 聊天历史区域 -->
            <div class="flex-1 overflow-y-auto p-4 md:p-6 bg-neutral-50 scrollbar-hide" id="chat-history">
                <!-- 对话历史将通过 JS 动态填充 -->
                <div class="max-w-3xl mx-auto mb-8 mt-4">
                    <div class="agent-message bg-white rounded-xl p-4 shadow-card border border-neutral-200 mb-6 inline-block">
                        <div class="flex items-center mb-2">
                            <div class="w-8 h-8 rounded-full bg-primary/10 flex items-center justify-center text-primary mr-3">
                                <i class="fa fa-robot"></i>
                            </div>
                            <span class="font-medium text-neutral-700">助手</span>
                        </div>
                        <div class="text-neutral-600 text-balance">你好！我是低空导航知识库助手。请选择一个会话或新建一个会话开始对话。</div>
                    </div>
                </div>
            </div>

            <!-- 输入区域 -->
            <div class="border-t border-neutral-200 bg-white p-4 md:p-6">
                <div class="max-w-3xl mx-auto">
                    <div class="relative">
                        <textarea 
                            id="user-input" 
                            placeholder="输入你的问题..." 
                            class="w-full px-4 py-3 pr-12 rounded-xl border border-neutral-300 focus:border-primary focus:ring-2 focus:ring-primary/20 outline-none transition-all duration-200 resize-none min-h-[60px] max-h-[200px] scrollbar-hide"
                            autocomplete="off"
                        ></textarea>
                        <button id="send-btn" class="absolute right-3 bottom-3 bg-primary hover:bg-primary/90 text-white rounded-full w-9 h-9 flex items-center justify-center transition-all duration-200 shadow-sm hover:shadow">
                            <i class="fa fa-paper-plane-o"></i>
                        </button>
                    </div>
                    <p class="text-xs text-neutral-400 mt-2 text-center">
                        提示：输入问题后按Enter发送，Shift+Enter换行
                    </p>
                </div>
            </div>
        </main>
    </div>

    <script>
        // 全局变量
        let currentSessionId = null;

        // DOM 元素
        const sessionListElement = document.getElementById('session-list');
        const chatHistoryElement = document.getElementById('chat-history');
        const userInputElement = document.getElementById('user-input');
        const sendButtonElement = document.getElementById('send-btn');
        const newSessionButton = document.getElementById('new-session-btn');
        const sessionCountElement = document.getElementById('session-count');
        const sidebarElement = document.getElementById('sidebar');
        const sidebarToggleElement = document.getElementById('sidebar-toggle');
        // 清除所有会话按钮点击事件
        const clearAllBtn = document.getElementById('clear-all-sessions-btn');
        if (clearAllBtn) {
            clearAllBtn.addEventListener('click', clearAllSessions);
        }
        // --- 辅助函数 ---

        // 格式化时间戳
        function formatTime(timestampStr) {
            const date = new Date(timestampStr);
            return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
        }

        // 格式化日期（用于会话列表）
        function formatDate(timestampStr) {
            const date = new Date(timestampStr);
            const now = new Date();
            const yesterday = new Date(now);
            yesterday.setDate(yesterday.getDate() - 1);

            if (date.toDateString() === now.toDateString()) {
                return '今天 ' + formatTime(timestampStr);
            } else if (date.toDateString() === yesterday.toDateString()) {
                return '昨天 ' + formatTime(timestampStr);
            } else {
                return date.toLocaleDateString('zh-CN') + ' ' + formatTime(timestampStr);
            }
        }

        // 滚动聊天历史到底部
        function scrollToBottom() {
            chatHistoryElement.scrollTop = chatHistoryElement.scrollHeight;
        }

        // 显示加载指示器
        function showLoading() {
            const loadingElement = document.createElement('div');
            loadingElement.className = 'max-w-3xl mx-auto mb-6';
            loadingElement.innerHTML = `
                <div class="agent-message bg-white rounded-xl p-4 shadow-card border border-neutral-200 inline-block">
                    <div class="flex items-center mb-2">
                        <div class="w-8 h-8 rounded-full bg-primary/10 flex items-center justify-center text-primary mr-3">
                            <i class="fa fa-robot"></i>
                        </div>
                        <span class="font-medium text-neutral-700">助手</span>
                    </div>
                    <div class="flex space-x-1">
                        <div class="w-2 h-2 bg-neutral-400 rounded-full animate-bounce" style="animation-delay: 0ms"></div>
                        <div class="w-2 h-2 bg-neutral-400 rounded-full animate-bounce" style="animation-delay: 150ms"></div>
                        <div class="w-2 h-2 bg-neutral-400 rounded-full animate-bounce" style="animation-delay: 300ms"></div>
                    </div>
                </div>
            `;
            loadingElement.id = 'loading-indicator';
            chatHistoryElement.appendChild(loadingElement);
            scrollToBottom();
            sendButtonElement.disabled = true;
            userInputElement.disabled = true;
        }

        // 隐藏加载指示器
        function hideLoading() {
            const loadingElement = document.getElementById('loading-indicator');
            if (loadingElement) {
                loadingElement.remove();
            }
            sendButtonElement.disabled = false;
            userInputElement.disabled = false;
            userInputElement.focus();
        }

        // --- API 调用函数 ---

        // 获取会话列表
        async function fetchSessions() {
            try {
                const response = await fetch('/api/sessions', { method: 'GET' });
                if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
                const sessions = await response.json();
                renderSessionList(sessions);
                // 更新会话计数
                sessionCountElement.textContent = `${sessions.length} 个会话`;
            } catch (error) {
                console.error('获取会话列表失败:', error);
            }
        }
        // 清空所有会话
        async function clearAllSessions() {
            // 先弹窗确认，防止误操作
            const confirmClear = confirm("确定要清除所有会话历史吗？此操作不可恢复！");
            if (!confirmClear) return;  // 用户取消则终止
        
            try {
                const response = await fetch('/api/clear_all_sessions', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' }
                });
                const data = await response.json();
        
                if (data.status === 'success') {
                    // 清空成功：更新UI
                    alert(data.message);  // 提示用户（可选，也可用 Toast 优化）
                    currentSessionId = null;  // 重置当前会话ID
                    await fetchSessions();  // 重新获取会话列表（此时已为空）
                    fetchChatHistory(null);  // 清空聊天历史区域
                } else {
                    // 清空失败：提示错误
                    alert(`清空失败: ${data.message}`);
                }
            } catch (error) {
                console.error('清空会话出错:', error);
                alert('清空会话时发生网络错误，请重试！');
            }
        }
        
        // 获取指定会话的聊天历史
        async function fetchChatHistory(sessionId) {
            if (!sessionId) {
                chatHistoryElement.innerHTML = `
                    <div class="max-w-3xl mx-auto mb-8 mt-4">
                        <div class="agent-message bg-white rounded-xl p-4 shadow-card border border-neutral-200 mb-6 inline-block">
                            <div class="flex items-center mb-2">
                                <div class="w-8 h-8 rounded-full bg-primary/10 flex items-center justify-center text-primary mr-3">
                                    <i class="fa fa-robot"></i>
                                </div>
                                <span class="font-medium text-neutral-700">助手</span>
                            </div>
                            <div class="text-neutral-600">${marked.parse('请选择一个会话或新建一个会话。')}</div>
                        </div>
                    </div>
                `;
                return;
            }
            try {
                const response = await fetch(`/api/history/${sessionId}`, { method: 'GET' });
                if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
                const history = await response.json();
                renderChatHistory(history);
            } catch (error) {
                console.error('获取聊天历史失败:', error);
                chatHistoryElement.innerHTML = `
                    <div class="max-w-3xl mx-auto mb-8 mt-4">
                        <div class="agent-message bg-white rounded-xl p-4 shadow-card border border-neutral-200 mb-6 inline-block">
                            <div class="flex items-center mb-2">
                                <div class="w-8 h-8 rounded-full bg-primary/10 flex items-center justify-center text-primary mr-3">
                                    <i class="fa fa-robot"></i>
                                </div>
                                <span class="font-medium text-neutral-700">助手</span>
                            </div>
                            <div class="text-neutral-600">${marked.parse('加载聊天历史失败。')}</div>
                        </div>
                    </div>
                `;
            }
        }

        // 发送用户消息
        async function sendMessage(message, sessionId) {
            if (!message || !sessionId) return;

            // 1. 立即在界面上显示用户消息
            addMessageToChat('user', message, new Date().toISOString());

            // 2. 显示加载指示器
            showLoading();

            // 3. 发送请求到后端
            try {
                const response = await fetch('/api/chat', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ message: message, session_id: sessionId })
                });

                if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
                const data = await response.json();

                // 4. 隐藏加载指示器
                hideLoading();

                // 5. 显示 Agent 回复
                addMessageToChat('agent', data.response, data.timestamp);

                // 6. 刷新会话列表
                await fetchSessions();

            } catch (error) {
                console.error('发送消息失败:', error);
                hideLoading();
                // 显示错误消息
                addMessageToChat('agent', '抱歉，发送消息时出错。', new Date().toISOString());
            }
        }

        // 新建会话
        async function createNewSession() {
            try {
                const response = await fetch('/api/new_session', { method: 'POST' });
                if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
                const data = await response.json();
                const newSessionId = data.session_id;

                // 切换到新会话
                currentSessionId = newSessionId;
                await fetchSessions();
                await fetchChatHistory(currentSessionId);

                // 在移动设备上创建会话后自动隐藏侧边栏
                if (window.innerWidth < 768) {
                    toggleSidebar();
                }

            } catch (error) {
                console.error('创建新会话失败:', error);
                alert('创建新会话失败。');
            }
        }

        // 切换侧边栏显示（移动端）
        function toggleSidebar() {
            sidebarElement.classList.toggle('hidden');
            sidebarElement.classList.toggle('absolute');
            sidebarElement.classList.toggle('inset-0');
            sidebarElement.classList.toggle('z-30');
            sidebarElement.classList.toggle('w-full');
        }

        // --- 渲染函数 ---

        // 渲染会话列表
        function renderSessionList(sessions) {
            sessionListElement.innerHTML = '';
            if (sessions.length === 0) {
                sessionListElement.innerHTML = `
                    <div class="text-neutral-400 text-center py-10">
                        <i class="fa fa-comments-o text-4xl mb-3 opacity-30"></i>
                        <p>暂无会话记录</p>
                    </div>
                `;
                return;
            }

            // 按时间排序，最新的在前面
            sessions.sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp));

            sessions.forEach(session => {
                const sessionElement = document.createElement('div');
                sessionElement.className = `session-item rounded-lg p-3 mb-1 cursor-pointer transition-all duration-200 ${session.id === currentSessionId ? 'bg-primary/5 border-l-4 border-primary' : 'hover:bg-neutral-50'}`;
                sessionElement.dataset.sessionId = session.id;

                // 截断长标题
                let displayTitle = session.title.length > 30 ? session.title.substring(0, 30) + '...' : session.title;

                sessionElement.innerHTML = `
                    <div class="flex justify-between items-start">
                        <div class="font-medium text-neutral-700 text-sm truncate max-w-[160px]">${displayTitle}</div>
                        <span class="text-xs text-neutral-400">${formatTime(session.timestamp)}</span>
                    </div>
                    <div class="text-xs text-neutral-500 mt-1 line-clamp-1">${formatDate(session.timestamp)}</div>
                `;

                sessionElement.addEventListener('click', () => {
                    currentSessionId = session.id;
                    // 更新UI高亮
                    document.querySelectorAll('.session-item').forEach(item => {
                        item.classList.remove('bg-primary/5', 'border-l-4', 'border-primary');
                        item.classList.add('hover:bg-neutral-50');
                    });
                    sessionElement.classList.add('bg-primary/5', 'border-l-4', 'border-primary');
                    sessionElement.classList.remove('hover:bg-neutral-50');
                    // 加载聊天历史
                    fetchChatHistory(currentSessionId);

                    // 在移动设备上选择会话后自动隐藏侧边栏
                    if (window.innerWidth < 768) {
                        toggleSidebar();
                    }
                });

                sessionListElement.appendChild(sessionElement);
            });
        }

        // 渲染聊天历史
        function renderChatHistory(history) {
            chatHistoryElement.innerHTML = '';
            if (history.length === 0) {
                chatHistoryElement.innerHTML = `
                    <div class="max-w-3xl mx-auto mb-8 mt-4">
                        <div class="agent-message bg-white rounded-xl p-4 shadow-card border border-neutral-200 mb-6 inline-block">
                            <div class="flex items-center mb-2">
                                <div class="w-8 h-8 rounded-full bg-primary/10 flex items-center justify-center text-primary mr-3">
                                    <i class="fa fa-robot"></i>
                                </div>
                                <span class="font-medium text-neutral-700">助手</span>
                            </div>
                            <div class="text-neutral-600">${marked.parse('开始对话吧！')}</div>
                        </div>
                    </div>
                `;
                scrollToBottom();
                return;
            }

            history.forEach(turn => {
                // 显示用户消息
                addMessageToChat('user', turn.user, turn.timestamp);
                // 显示助手消息
                addMessageToChat('agent', turn.agent, turn.timestamp);
            });
            scrollToBottom();
        }

        // 将单条消息添加到聊天历史
        function addMessageToChat(sender, content, timestamp) {
            const messageContainer = document.createElement('div');
            messageContainer.className = `max-w-3xl mx-auto mb-6 animate-fadeIn`;

            const timeStr = formatTime(timestamp);
            const isUser = sender === 'user';

            // 使用marked解析MD格式文本
            const parsedContent = marked.parse(content);

            messageContainer.innerHTML = `
                <div class="${isUser ? 'flex justify-end' : ''}">
                    <div class="${isUser ? 'user-message bg-primary text-white' : 'agent-message bg-white border border-neutral-200 text-neutral-700'} rounded-xl p-4 shadow-card max-w-[85%]">
                        <div class="flex ${isUser ? 'justify-between' : 'items-center'} mb-2">
                            ${!isUser ? `
                                <div class="w-8 h-8 rounded-full bg-primary/10 flex items-center justify-center text-primary mr-3">
                                    <i class="fa fa-robot"></i>
                                </div>
                                <span class="font-medium">助手</span>
                            ` : `
                                <span class="font-medium">你</span>
                            `}
                            <span class="text-xs opacity-70">${timeStr}</span>
                        </div>
                        <div class="text-balance">${parsedContent}</div>
                    </div>
                </div>
            `;

            chatHistoryElement.appendChild(messageContainer);
            scrollToBottom();
        }

        // 自动调整文本框高度
        function adjustTextareaHeight() {
            userInputElement.style.height = 'auto';
            userInputElement.style.height = (Math.min(userInputElement.scrollHeight, 200)) + 'px';
        }

        // --- 事件监听器 ---

        // 发送按钮点击事件
        sendButtonElement.addEventListener('click', () => {
            const message = userInputElement.value.trim();
            if (message && currentSessionId) {
                sendMessage(message, currentSessionId);
                userInputElement.value = '';
                adjustTextareaHeight();
            } else if(!currentSessionId) {
                alert('请先选择或创建一个会话。');
            }
        });

        // 回车发送消息
        userInputElement.addEventListener('keydown', (e) => {
            adjustTextareaHeight();

            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                sendButtonElement.click();
            }
        });

        // 新建会话按钮点击事件
        newSessionButton.addEventListener('click', createNewSession);

        // 侧边栏切换按钮（移动端）
        sidebarToggleElement.addEventListener('click', toggleSidebar);

        // 窗口大小变化时处理
        window.addEventListener('resize', () => {
            if (window.innerWidth >= 768) {
                sidebarElement.classList.remove('hidden', 'absolute', 'inset-0', 'z-30', 'w-full');
                sidebarElement.classList.add('flex');
            } else if (currentSessionId) {
                sidebarElement.classList.add('hidden');
                sidebarElement.classList.remove('absolute', 'inset-0', 'z-30', 'w-full', 'flex');
            }
        });

        // --- 初始化 ---
        window.addEventListener('DOMContentLoaded', async () => {
            await fetchSessions();
            adjustTextareaHeight();
            userInputElement.focus();

            // 为textarea添加初始高度调整
            userInputElement.addEventListener('input', adjustTextareaHeight);
        });

        // 添加淡入动画
        const style = document.createElement('style');
        style.textContent = `
            @keyframes fadeIn {
                from { opacity: 0; transform: translateY(10px); }
                to { opacity: 1; transform: translateY(0); }
            }
            .animate-fadeIn {
                animation: fadeIn 0.3s ease-out forwards;
            }
        `;
        document.head.appendChild(style);
    </script>
</body>
</html>
"""


# --- Flask 路由 ---

@app.route("/")
def index():
    """主页面"""
    # 可以在这里从 Flask session 中尝试获取 currentSessionId
    # session_id = session.get('current_session_id')
    # if session_id:
    #     history_memory.set_current_session(session_id)
    return render_template_string(HTML_TEMPLATE)


# --- API 路由 ---

@app.route("/api/sessions", methods=["GET"])
def api_get_sessions():
    """API: 获取会话列表"""
    sessions_list = history_memory.get_sessions_list()
    return jsonify(sessions_list)


@app.route("/api/history/<session_id>", methods=["GET"])
def api_get_history(session_id):
    """API: 获取指定会话的聊天历史"""
    history = history_memory.get_history(session_id)
    return jsonify(history)


@app.route("/api/chat", methods=["POST"])
def api_chat():
    """API: 处理聊天消息"""
    data = request.get_json()
    user_message = data.get("message")
    session_id = data.get("session_id")

    if not user_message or not session_id:
        return jsonify({"error": "缺少消息或会话ID"}), 400

    # 1. 获取上下文
    context = history_memory.get_context(session_id, last_n=3)  # 获取最近3轮上下文

    # 2. 调用你的 Agent (这里用模拟函数)
    # agent_response = enterprise_agent.execute_query(user_message, context=context)
    # agent_response = mock_agent_execute(user_message, context=context)
    agent_response = real_agent_execute(user_message, context=context)  # <-- 使用真实函数

    # 3. 将对话轮次添加到历史记录
    history_memory.add_turn(user_message, agent_response, session_id)

    # 4. 返回响应
    # 注意：实际应用中，Agent 可能会返回时间戳，这里我们用当前时间
    import datetime
    response_timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    return jsonify({"response": agent_response, "timestamp": response_timestamp})


@app.route("/api/new_session", methods=["POST"])
def api_new_session():
    """API: 创建新会话"""
    new_session_id = history_memory.start_new_session()
    # 将新会话ID存入 Flask session (可选)
    # session['current_session_id'] = new_session_id
    return jsonify({"session_id": new_session_id})

@app.route("/api/clear_all_sessions", methods=["POST"])
def api_clear_all_sessions():
    """API: 清空所有会话历史"""
    try:
        # 调用 HistoryMemory 的清空方法
        history_memory.clear_all_sessions()
        # 返回成功响应（前端需根据此更新UI）
        return jsonify({"status": "success", "message": "所有会话已清空"})
    except Exception as e:
        # 捕获异常，返回错误信息
        print(f"清空会话出错: {e}")
        return jsonify({"status": "error", "message": f"清空失败: {str(e)}"}), 500

# 可以添加更多 API 路由，如删除会话、清空会话等
#豆包美化版
if __name__ == "__main__":
    # 确保在非调试模式下也能重新加载模块（如果需要）
    # debug=True 会启用重载，但注意它会重启应用，可能影响 session 状态
    app.run(host="0.0.0.0", port=int(os.environ.get("PORT", 5000)), debug=False)
